/**
 * 系统框架servlet
 */

package ms.core.gateway.servlet;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ms.core.common.ApiResult;
import ms.core.common.consts.SysErr;
import ms.core.common.utils.ResponseUtils;
import ms.core.gateway.dto.Api;
import ms.core.gateway.system.Application;
import ms.core.tool.StrTool;

/**
 * Servlet implementation class CoreServlet
 */
public class CoreServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public CoreServlet() {
        super();
    }

    private void doResponse(HttpServletRequest req, HttpServletResponse resp) {
    	String fn = req.getParameter("fn");
    	if (StrTool.isBlank(fn)) {
    		ResponseUtils.doResponse(resp, 200, new ApiResult(false, SysErr.SYS_UNKNOWN_FUNC));
    		return;
    	}
        
    	/**判断是否支持异步请求方式(system.properties配置了asyncServlet=true同时web.xml配置<async-supported>true</async-supported>)*/
    	if (Application.ASYNC_SERVLET && req.isAsyncSupported()) {
    		//进入异步模式
    		AsyncContext ctx = req.startAsync();
    		if (req.isAsyncStarted()) Application.executeRequest(Api.SYS_API, fn, ctx);
    	} else {
    		Application.executeRequest(Api.SYS_API, fn, req, resp);
    	}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doResponse(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doResponse(request, response);
	}

}
